package com.pro01.backend.controller;

import com.pro01.backend.dto.MessageDTO;
import com.pro01.backend.pojo.Message;
import com.pro01.backend.pojo.MessageConversation;
import com.pro01.backend.pojo.PageResult;
import com.pro01.backend.pojo.Result;
import com.pro01.backend.service.MessageService;
import com.pro01.backend.utils.TokenUtil;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.Map;

@RestController
@RequestMapping("/messages")
public class MessageController {

    @Autowired
    private MessageService messageService;

    /**
     * 发送私信
     */
    @PostMapping
    public Result<Void> sendMessage(@RequestBody Message message,
                                    HttpServletRequest request) {
        try {
            Long senderId = TokenUtil.getUserId(request); // 当前登录用户ID
            message.setSenderId(senderId);

            if (message.getReceiverId() == null || message.getContent() == null || message.getContent().trim().isEmpty()) {
                return Result.error("收件人和内容不能为空");
            }

            messageService.sendMessage(message);
            return Result.success();
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error("发送私信失败：" + e.getMessage());
        }
    }

    /**
     * 查看收件箱（分页）
     */
    @GetMapping("/received")
    public Result<PageResult<Message>> getReceivedMessages(
            @RequestParam(defaultValue = "1") int pageNum,
            @RequestParam(defaultValue = "10") int pageSize,
            HttpServletRequest request) {
        try {
            Long receiverId = TokenUtil.getUserId(request); // 当前登录用户
            PageResult<Message> pageResult = messageService.getReceivedMessages(receiverId, pageNum, pageSize);
            return Result.success(pageResult);
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error("获取收件箱失败：" + e.getMessage());
        }
    }

    /**
     * 查看发件箱（分页）
     */
    @GetMapping("/sent")
    public Result<PageResult<Message>> getSentMessages(
            @RequestParam(defaultValue = "1") int pageNum,
            @RequestParam(defaultValue = "10") int pageSize,
            HttpServletRequest request) {
        try {
            Long senderId = TokenUtil.getUserId(request); // 当前登录用户
            PageResult<Message> pageResult = messageService.getSentMessages(senderId, pageNum, pageSize);
            return Result.success(pageResult);
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error("获取发件箱失败：" + e.getMessage());
        }
    }

    /**
     * 用户将私信标记为已读
     */
    @PutMapping("/{messageId}/read")
    public Result<Void> markMessageAsRead(@PathVariable Long messageId,
                                          HttpServletRequest request) {
        try {
            Long receiverId = TokenUtil.getUserId(request); // 当前登录用户
            messageService.markAsRead(messageId, receiverId);
            return Result.success();
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error("标记消息为已读失败：" + e.getMessage());
        }
    }

    /**
     * 用户删除自己能看到的私信
     */
    @DeleteMapping("/{messageId}")
    public Result<Void> deleteMessage(@PathVariable Long messageId,
                                      HttpServletRequest request) {
        try {
            Long userId = TokenUtil.getUserId(request); // 当前登录用户
            messageService.deleteMessage(messageId, userId);
            return Result.success();
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error("删除消息失败：" + e.getMessage());
        }
    }

    /**
     * 查询当前用户未读私信数量
     */
    @GetMapping("/unread/count")
    public Result<Integer> getUnreadMessageCount(HttpServletRequest request) {
        try {
            Long receiverId = TokenUtil.getUserId(request); // 当前登录用户
            int unreadCount = messageService.getUnreadCount(receiverId);
            return Result.success(unreadCount);
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error("获取未读消息数量失败：" + e.getMessage());
        }
    }

    /**
     * 用户查看会话列表
     */
    @GetMapping("/conversations")
    public Result<PageResult<MessageConversation>> getConversations(
            @RequestParam(defaultValue = "1") int pageNum,
            @RequestParam(defaultValue = "10") int pageSize,
            HttpServletRequest request) {
        try {
            Long userId = TokenUtil.getUserId(request);
            PageResult<MessageConversation> pageResult = messageService.getConversations(userId, pageNum, pageSize);
            return Result.success(pageResult);
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error("获取会话列表失败：" + e.getMessage());
        }
    }

    /**
     * 查看与某个用户的聊天记录（分页）
     */
//    @GetMapping("/conversation/{otherUserId}")
//    public Result<PageResult<Message>> getConversation(@PathVariable Long otherUserId,
//                                                       @RequestParam(defaultValue = "1") int pageNum,
//                                                       @RequestParam(defaultValue = "10") int pageSize,
//                                                       HttpServletRequest request) {
//        try {
//            Long userId = TokenUtil.getUserId(request); // 当前登录用户
//            PageResult<Message> pageResult = messageService.getConversation(userId, otherUserId, pageNum, pageSize);
//            return Result.success(pageResult);
//        } catch (Exception e) {
//            e.printStackTrace();
//            return Result.error("获取聊天记录失败：" + e.getMessage());
//        }
//    }
    @GetMapping("/conversation/{otherUserId}")
    public Result<PageResult<MessageDTO>> getConversation(@PathVariable Long otherUserId,
                                                          @RequestParam(defaultValue = "1") int pageNum,
                                                          @RequestParam(defaultValue = "10") int pageSize,
                                                          HttpServletRequest request) {
        Long userId = TokenUtil.getUserId(request);
        PageResult<MessageDTO> pageResult = messageService.getConversation(userId, otherUserId, pageNum, pageSize);
        return Result.success(pageResult);
    }

    // 初始化聊天
    @PostMapping("/init")
    public Result<Void> initConversation(@RequestBody Map<String, Long> body, HttpServletRequest request) {
        Long senderId = TokenUtil.getUserId(request);
        Long receiverId = body.get("receiverId");

        if (receiverId == null) {
            return Result.error("收件人 ID 不能为空");
        }

        try {
            messageService.initConversationIfAbsent(senderId, receiverId);
            return Result.success();
        } catch (RuntimeException e) {
            return Result.error("会话初始化失败：" + e.getMessage());
        }
    }


}
